package com.queen.restaurant.service;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.queen.restaurant.dao.OrderDao;
import com.queen.restaurant.dao.OrderItemDao;
import com.queen.restaurant.domain.Order;
import com.queen.restaurant.domain.OrderItem;
import com.queen.restaurant.domain.Restaurant;
import com.queen.restaurant.domain.Table;
import com.queen.restaurant.domain.User;

@Service
public class OrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private OrderItemDao orderItemDao;
	@Autowired
	private UserService userService;
	@Autowired
	private TableService tableService;
	
	public Order createOrder(String userId, String tableId){
		User user = userService.getUserById(userId);
		Table table = tableService.getTableById(tableId);
		table.setTableStatus(Table.TABLE_STATUS_USING);
		Restaurant restaurant = table.getRestaurant();
		
		Order order = new Order();
		order.setUser(user);
		order.setTable(table);
		order.setRestaurant(restaurant);
		
		SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前系统日期
		String orderTime = dateFm.format(new java.util.Date());
		
		order.setOrderTime(orderTime);
		orderDao.save(order);
		return order;
	}
	
	public void commitOrder(Order order){
		for (OrderItem orderItem : order.getOrderItemList()) {
			orderItemDao.save(orderItem);
		}
		orderDao.update(order);
	}
	
	public void cancelOrder(String orderId){
		Order order = orderDao.get(orderId);
		Table table = order.getTable();
		table.setTableStatus(Table.TABLE_STATUS_FREE);
		tableService.updateTable(table);
		
		orderDao.remove(order);
	}
	
	public void payOrder(Order order){
		//更改餐桌状态
		Table table = order.getTable();
		table.setRestaurant(order.getRestaurant());
		table.setTableStatus(Table.TABLE_STATUS_FREE);
		tableService.updateTable(table);
		//增加用户积分
		int credit = order.getUser().getCredit();
		credit += (order.getTotal() * 100);
		User user = order.getUser();
		user.setCredit(credit);
		userService.updateUser(user);
		
		//让订单可被评论
		order.setCanComment(true);
		for (OrderItem orderItem : order.getOrderItemList()) {
			orderItem.setCanComment(true);
			orderItemDao.update(orderItem);
		}
		
		//订单更改为已支付
		order.setIsPay(true);
		orderDao.update(order);
	}
	
	public List<Order> getUserOrderList(String userId){
		return orderDao.getOrderListByUserId(userId);
	}
	
	public Order getOrderByOrderId(String orderId){
		return orderDao.get(orderId);
	}
}
